package tron.config;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;


/**
 * 日志切面
 */
@Component
@Aspect
public class LogAop {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(* tron.controller.*.*(..))")
    public void logPointcut() { }

    @Around(value = "logPointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Instant start = Instant.now();
        Object[] args = proceedingJoinPoint.getArgs();
        StringBuilder functionName = new StringBuilder();
        Signature signature = proceedingJoinPoint.getSignature();
        functionName.append(signature.getDeclaringTypeName()).append(StringPool.DOT).append(signature.getName());
        Object result = null;
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            // todo 方法调用异常，记录到错误日志服务器

            log.info("{}方法被调用，调用失败{} 参数：{}",functionName.toString(),throwable.getMessage(),args);


            throw  throwable;
        }finally {
            Instant end = Instant.now();
            log.info("{}方法执行时间：{}", functionName.toString(),Duration.between(start,end).toMillis());
        }
        // todo 记录到审计日志服务器
        log.info("{}方法被调用，调用成功 参数：{}",functionName.toString(),args);
        return result;
    }
}
